var express = require('express');
var router = express.Router();
var { userModel,goodcarmodel,address } = require('../../model/model')
var jwt = require("jsonwebtoken")
const { generateToken } = require("../../util/jwt")
const SMSClient = require('@alicloud/sms-sdk');
const { checkAuth } = require("../../middleware/token")
const { ACCESS_KEY, REFRESH_KEY } = require("../../config/keys")
const AlipayFormData = require('alipay-sdk/lib/form').default
const alipaySdk = require('./alipay')
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
//六位验证码
function getCode() {
    let str = "";
    for (let i = 0; i < 6; i++) {
        str += parseInt(Math.random() * 10)
    }
    return str;
}
//手机号验证码
let msm = ''
router.post('/get_sms', function (req, res, next) {
    console.log("oooo")
    let phoneNum = req.body.phone;
    //获取前端参数phone
    //   console.log("手机号码", phoneNum);
    //初始化sms_client
    let smsClient = new SMSClient({
        accessKeyId: 'LTAI5tRbhCQKgRiaKeW4T1Cn',  //accessKeyId 前面提到要准备的
        secretAccessKey: 'ETWmzUPZCJvOBcJ3e50cWZSg4BCjOo'  //secretAccessKey 前面提到要准备的
    });
    let str = getCode();
    msm = str;
    // 开始发送短信
    smsClient.sendSMS({
        PhoneNumbers: phoneNum,
        SignName: "手机验证码登录0909", //签名名称 前面提到要准备的
        TemplateCode: "SMS_472315331", //模版CODE  前面提到要准备的
        TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
    }).then(result => {
        console.log("result", result)
        let { Code } = result;
        if (Code == 'OK') {
            res.send({
                code: 0,
                msg: 'success',
                sms: str
            })
            console.log(result)
        }
    }).catch(err => {
        console.log(err);
        res.send({
            code: 1,
            msg: 'fail: ' + err.data.Message
        })
    });
})
//手机号登录+验证码对比过程
router.post('/login_phone', async (req, res) => {
    let { phone, yanzhengma } = req.body
    if (yanzhengma == "11111") {
        let user = await userModel.findOne({ phone: phone })
        if (user) {
            const pyload = {
                username: user.username,
                password: user.password,
                phone: phone
            }
            const accessToken = generateToken(pyload, ACCESS_KEY, "3s")
            const refreshToken = generateToken(pyload, REFRESH_KEY, "60s")
            res.send({
                code: 200,
                msg: '登录成功',
                id: user._id,
                data: user,
                token: {
                    accessToken,
                    refreshToken
                }
            }
            )
        } else {
            res.json({
                code: 1,
                msg: '用户不存在'
            })
        }
    } else {
        res.send({
            code: 403,
            msg: '验证码错误'
        })
    }
});
router.post('/zhuce', async (req, res) => {
    let { phone } = req.body
    let user = await userModel.findOne({ phone: phone })
    if (user) {
        res.send({
            code: 1,
            msg: '用户已存在'
        })
    } else {
        let obj = {
            phone: phone,
            username: Date.now(),
            password: 123, //默认密码123
        }
        await userModel.create(obj)
        res.send({
            code: 200,
        })
    }

})
//账号密码登录
// router.post('/login', async (req, res) => {
//   let { username, password } = req.body
//   let user = await userModel.findOne({ username: username, password: password })
//   if (user) {
//     let token = jwt.sign({ username: username }, 'secret', { expiresIn: '1h' })
//     res.send({ code: 200, msg: '登录成功', token: token })
//   } else {
//     res.send({ code: 400, msg: '登录失败' })
//   }
// })

router.get("/refresh_token", checkAuth(REFRESH_KEY), async (req, res) => {
    const { claim } = req
    const pyload = {
        name: claim.name,
        password: claim.password
    }
    const accessToken = generateToken(pyload, ACCESS_KEY, '1h')
    console.log("lalal")
    // const refreshToken = generateToken(pyload, REFRESH_KEY, 120)
    res.send({
        code: 200,
        msg: "刷新成功",
        token: {
            accessToken,
            // refreshToken
        }
    })
})
//人脸识别登录
router.post('/faceLogin', async (req, res) => {
    //获取前端传来的base64
    let b64 = req.body.b64
    const IaiClient = tencentcloud.iai.v20200303.Client;
    try {
        const clientConfig = {
            credential: {
                //自己的腾讯secretId
                secretId: "AKIDITQ7ctxqZ6h5HH6ukMlz9BCAD9ye9SWp",
                //自己的腾讯密匙
                secretKey: "DKI1Zv5A2ueBVfeSGxVvQ4b7Uj1Q1Rv3",
            },
            region: "ap-beijing",  //地域参数（华北地区北京）+
            profile: {
                httpProfile: {
                    endpoint: "iai.tencentcloudapi.com",
                },
            },
        };
        const client = new IaiClient(clientConfig);
        const params = {
            "GroupIds": [  //你创建的人员库ID
                "yzk_040909"
            ],
            "Image": b64,  //图片的base64格式编码
            "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
            "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
            "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
        };
        // console.log(params, 'params');
        let doc = await client.SearchFaces(params)
        // doc为人脸识别后的返回信息
        // console.log(doc, 'doc');
        if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
            let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
            console.log(personName, 'personNume');
            res.send({ code: 200, msg: "登录成功！", })
            let user = await userModel.find({ facename: personName })
            if (user.length != 0) {
                //生成<token> </token>
                let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })
                res.send({
                    code: 200,
                    msg: "登录成功！",
                    token,
                    _id: user[0]._id
                })
            }
        } else {
            res.send({
                code: 401,
                msg: '人脸库无此人！'
            })
            return false
        }
    } catch (err) {
        console.log(err);
    }

})
router.get('/gouwulist', async (req, res) => {
    let { id } = req.query
    console.log(id, 'id');
    let goodcar = await goodcarmodel.find({ ren: id })
    
    console.log(goodcar, 'goodcar');
    res.send({
        code: 200,
        msg: '查询成功',
        goodcar
    })
})
router.post('/gouwulist', async (req, res) => {
    let { id,count } = req.query
    await goodcarmodel.updateOne({_id:id},{num:count})
    res.send({
        code: 200,
        msg: '修改成功',
    })
})
router.post("/pcpay", async(req, res) => {
    const formData = new AlipayFormData()
    const price = req.query.price
    formData.setMethod('get');
    // 通过addField增加参数
    // 在用户支付完成之后，支付宝服务器会根据传入的notify_url,以post请求的形式将支付结果作为参数通知到商户系统
    // 支付成功或失败都返回
    formData.addField('returnUrl', "http://www.baidu.com");
    formData.addField('bizContent', {
        out_trade_no: '45416515616',//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
        product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
        total_amount: price,// 订单总金额
        subject: '1221',// 订单描述
        body: '34234',// 商品描述
    })
    // 返回promise
    const result = await alipaySdk.exec(
        'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
        {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
        { formData: formData }// result为可以跳转支付链接的url
    )
    // res.json({ url: result })
    res.send({
      code:200,
      result
    })

})
router.get('/dizhi', async (req, res) => {
    let list1 = await userModel.findOne({ _id: req.query.id })
    let list = await address.find({phone: list1.phone})
    // console.log(list1.list);
    res.send({
        code: 200,
        msg: '查询成功',
        list
    })
})
module.exports = router;





